
import { _decorator, Component, Node, CCFloat, find, BoxCollider2D, CCString, Vec3, RaycastResult2D, animation, Prefab, instantiate, CircleCollider2D, Vec2, PhysicsSystem2D, Collider2D } from 'cc';
import { Bullet } from '../Bullet';
import { bulletList, ColliderTag, ObjectLife } from '../Globle';
import { MoveObject } from '../MoveObject';
import { Enemy } from './Enemy';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = EnemyPeople
 * DateTime = Tue Jan 11 2022 16:14:13 GMT+0800 (中国标准时间)
 * Author = lyps
 * FileBasename = EnemyPeople.ts
 * FileBasenameNoExtension = EnemyPeople
 * URL = db://assets/Scripts/animy/EnemyPeople.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('EnemyPeople')
export class EnemyPeople extends Enemy {
    @property(CCFloat) attack_area: number;
    @property(CCFloat) speed: number = 0.2;
    //攻击距离
    @property(CCFloat) fireDistance: number = 100;
    //子弹速度
    @property(CCFloat) bulletSpeed: number;
    @property(CCString) type: string;
    private fireDelay: number;
    private bullettime:number = 0;
    private bulletnum:number = 0;
    @property(Prefab) bullet: Prefab;
    private lv: number = 2;
    private player: Node;
    private collider: BoxCollider2D;
    private frime_time: number = 0;
    private isDied: boolean = false;
    private life = ObjectLife.EnemyPeople;
    private animator: animation.AnimationController;
    private playerPosition: Vec3;
    private gameScene: Node;
    private current_direction: Vec2;
    private rayCastArr = [
        new Vec2(0, 5),
        new Vec2(5, 5),
        new Vec2(5, 0),
        new Vec2(5, -5),
        new Vec2(0, -5),
        new Vec2(-5, -5),
        new Vec2(-5, 0),
        new Vec2(-5, 5)
    ]
    onLoad() {
        this.fireDelay = Math.random() * 2 + 1;
        this.current_direction = this.rayCastArr[Math.floor(Math.random() * 8)]
    }
    start() {
        this.collider = this.getComponent(BoxCollider2D);
        this.collider.tag = ColliderTag.enemy_people;
        this.animator = this.getComponent(animation.AnimationController);
        this.gameScene = find("GameScene");
    }

    public onContact(otherCollider: Collider2D) {
        if(this.isDied) return;
        switch(otherCollider.tag){
            case ColliderTag.player:
                this.died();
                break;
            case ColliderTag.playerBullet://玩家的子弹
                let obj:MoveObject = otherCollider.node.getComponent(MoveObject);
                if(!obj) obj = otherCollider.node.getComponent(MoveObject)
                this.life-=obj.ATK;
                if(this.life<=0) this.died();
                break;
        }
    }

    update(deltaTime: number) {
        if (this.isDied) return;
        this.frime_time += deltaTime;
        if (this.type == 'stop') {
            this.runStopModel(deltaTime);
        } else {
            //移动模式
            this.runMoveModel(deltaTime);
        }
        if (!this.player || !this.player.name) {
            if (!(this.player = find("GameScene/Player"))) return;
        }
        this.playerPosition = this.player.position;
    }

    private runMoveModel(deltaTime:number) {
        let rays = PhysicsSystem2D.instance.raycast(new Vec2(this.node.position.x, this.node.position.y), new Vec2(this.node.position.x + this.current_direction.x, this.node.position.y + this.current_direction.y));
        if (!rays || !rays.length) {
            if (this.frime_time >= this.fireDelay) {
                if (this.frime_time >= this.fireDelay + 2) {
                    if(this.runStopModel(deltaTime)){
                        let index = Math.floor(Math.random() * 8);
                        this.current_direction = this.rayCastArr[index];
                    }
                }
            } else {
                let dec = this.current_direction.clone().normalize()
                this.node.position = new Vec3(dec.x * this.speed + this.node.position.x, dec.y * this.speed + this.node.position.y);
            }

        } else {
            let index = Math.floor(Math.random() * 8);
            this.current_direction = this.rayCastArr[index];
        }
    }

    //定点模式
    private runStopModel(deltaTime:number) {
        if (this.frime_time >= this.fireDelay) {
            switch (this.lv) {
                case 1:
                    this.fire();
                    this.fireDelay = Math.random() * 2 + 1;
                    this.frime_time = 0;
                    return true;
                case 2:
                    if(this.bullettime==0){
                        if(!this.fire(true)){
                            this.bullettime = 0;
                            this.bulletnum = 0;
                            this.fireDelay = Math.random() * 2 + 1;
                            this.frime_time = 0;
                            return true;
                        }
                        this.bulletnum++;
                        if(this.bulletnum>=this.lv){
                            this.bullettime = 0;
                            this.bulletnum = 0;
                            this.fireDelay = Math.random() * 2 + 1;
                            this.frime_time = 0;
                            return true;
                        }
                    }
                    this.bullettime+=deltaTime;
                    if(this.bullettime>=0.1) this.bullettime = 0;
                    break;
            }
            

        }
        return false;
    }
    //开火
    private fire(randomSpeed: boolean = false) {
        let distance = this.node.position.clone().subtract(this.playerPosition).length();
        if (distance > this.attack_area) return false;
        this.animator.setValue('fire', true);
        let bullet: Node;
        if (bulletList.length) {
            bullet = bulletList.find(v => v.active == false);
            if (!bullet) {
                bullet = instantiate(this.bullet);
                bulletList.push(bullet);
                this.gameScene.addChild(bullet);
            }
        } else {
            bullet = instantiate(this.bullet);
            bulletList.push(bullet);
            this.gameScene.addChild(bullet);
        }
        bullet.position = this.node.position;
        bullet.active = true;
        let dx = this.playerPosition.x - this.node.position.x;
        let dy = this.playerPosition.y - this.node.position.y;
        let direction = new Vec2(dx, dy).normalize();
        bullet.getComponent(CircleCollider2D).tag = ColliderTag.enemyBullet;
        let bulletScript = bullet.getComponent(Bullet);
        if (randomSpeed) {
            bulletScript.speed = Math.random()+0.5 * this.bulletSpeed;
        } else {
            bulletScript.speed = this.bulletSpeed;
        }
        bulletScript.setDirection(direction, 'enemy', this.fireDistance);
        return true;
    }

    private died() {
        this.scheduleOnce(()=>this.node.destroy(),0.01)
    }
}
